from django import http
from django.core.cache import cache
from django.shortcuts import render
from django.views import View

from areas.models import Area
from meiduo_mall.utils.response_code import RET


class AreaView(View):
    def get(self, request):
        area_id = request.GET.get("area_id")
        if not area_id:
            # 先判断是否缓存
            province_list = cache.get('area_id')
            if province_list:
                data_dict = {
                    'code': RET.OK,
                    'province_list': province_list
                }
                return http.JsonResponse(data_dict)
            # 获取省
            provinces = Area.objects.filter(parent=None).all()
            province_list = []
            for province in provinces:
                item_dict = {
                    'id': province.id,
                    'name': province.name
                }
                province_list.append(item_dict)
            data_dict = {
                'code': RET.OK,
                'province_list': province_list
            }
            # 设置缓存
            cache.set('province_list', province_list)
            return http.JsonResponse(data_dict)
        else:
            # 获取市
            citie_list = cache.get('subs%s' % area_id)
            if citie_list:
                data_dict = {
                    'code': RET.OK,
                    'sub_data': {
                        'subs': citie_list
                    }
                }
                return http.JsonResponse(data_dict)
            cities = Area.objects.filter(parent=area_id).all()
            citie_list = []
            for citie in cities:
                city_dict = {
                    'id': citie.id,
                    'name': citie.name
                }
                citie_list.append(city_dict)
            data_dict = {
                'code': RET.OK,
                'sub_data': {
                    'subs': citie_list
                }
            }
            cache.set('subs%s' , citie_list)
        return http.JsonResponse(data_dict)

# Create your views here.
